package bootstrap

import (
	"blog/config"
	"blog/internal/database"
	"fmt"
	"github.com/redis/go-redis/v9"
	"gorm.io/gorm"
	"log"
)

type Context struct {
	Config      *config.Config
	Database    *gorm.DB
	Redis       *redis.Client
	Repos       *Repository
	Services    *Services
	Controllers *Controllers
}

func Bootstrap(cfg *config.Config) *Context {
	// 执行初始化...
	ctx := &Context{Config: cfg}
	var err error
	// 初始化数据库
	ctx.Database, err = database.NewPostgresDB(&cfg.Database)
	if err != nil {
		log.Fatal(fmt.Sprintf("init postgres db err: %v", err))
	}
	// 执行自动迁移
	database.AutoMigrations(ctx.Database)
	// 初始化redis
	ctx.Redis, err = database.NewRedis(&cfg.Redis)
	if err != nil {
		log.Fatal(fmt.Sprintf("init redis db err: %v", err))
	}

	ctx.Repos = NewRepository(ctx.Database)
	ctx.Services = newServices(ctx.Repos)
	ctx.Controllers = newControllers(ctx.Services)
	return ctx
}
